
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';
import LoginView from '@/views/login/index.vue';
//首页
import IndexView from '@/views/index/index.vue';
import useCounter from "@/stores/counter.ts";
import routerData, { type ListMenu } from '../index.ts';
import { recursion } from '../modules/common.ts/index.ts';
import { computed } from 'vue';
// import {} from "../stores/counter"
// import {} from "../"
const modules = import.meta.glob('../views/**/**.vue')
const routes = [
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/index',
    name: 'index',
    component: IndexView
  }
]
const useCounterState = computed(() => {
  return useCounter()
})
let routerDataDown = recursion(useCounterState.value.menuList)



const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(async (to, format, next) => {
  if (to.path == "/login") {
    next()
  } else if (to.path == "/" || to.path == '') {
    next({ path: "/" })
  } else if (router.getRoutes().length === 3) {
    // let routerDataDown: Array<RouteRecordRaw | ListMenu> = routerData
    // routerDataDown = recursion(routerData)

    routerDataDown.forEach((route) => {
      if (route.component) {
        (route.component) = modules[`../views/${route.component}.vue`]
        router.addRoute('index', route)
      }
    })
    next({
      ...to,
      replace: true // 重定向,为了让刚刚添加的路由规则生效
    });
  } else {
    next()
  }

})

export default router 